package com.lw.service.impl;

import com.lw.common.vo.UserVo;
import com.lw.entity.*;
import com.lw.entity.table.TbMenuTableDef;
import com.lw.entity.table.TbRoleMenuTableDef;
import com.lw.entity.table.TbRoleTableDef;
import com.lw.entity.table.TbUserTableDef;
import com.lw.service.TbRoleMenuService;
import com.lw.service.TbRoleService;
import com.lw.service.TbUserInterfaceService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.lw.mapper.TbUserMapper;
import com.lw.service.TbUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户表 服务层实现。
 *
 * @author lw
 * @since 2025年04月29日 10:54:31
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {


    @Resource
    private TbRoleMenuService tbRoleMenuService;

    @Resource
    private TbUserInterfaceService tbUserInterfaceService;


    /**
     * todo 经典案例
     * mybatis-flex 关联查询案例
     *
     * @return 用户详情信息列表
     * by lw on 2024年8月3日 20:12:47
     */
    @Override
    public List<UserVo> getUserDetail() {
        return queryChain().select(TbUserTableDef.TB_USER.ALL_COLUMNS,
                        TbRoleTableDef.TB_ROLE.NAME.as("roleName"))
                .from(TbUserTableDef.TB_USER)
                .leftJoin(TbRoleTableDef.TB_ROLE)
                .on(TbUserTableDef.TB_USER.ROLE_ID.eq(TbRoleTableDef.TB_ROLE.ID)).listAs(UserVo.class);
    }

    @Override
    public List<TbMenu> getUserPermission(Integer roleId) {
        //查询用户权限
        List<TbMenu> tbMenuList = queryChain().select(TbMenuTableDef.TB_MENU.ALL_COLUMNS)
                .from(TbRoleMenuTableDef.TB_ROLE_MENU)
                .leftJoin(TbMenuTableDef.TB_MENU)
                .on(TbRoleMenuTableDef.TB_ROLE_MENU.MENU_ID.eq(TbMenuTableDef.TB_MENU.ID))
                .where(TbRoleMenuTableDef.TB_ROLE_MENU.ROLE_ID.eq(roleId)).listAs(TbMenu.class);
        return tbMenuList;
    }

    @Override
    @Transactional
    public int saveAndInterface(TbUser tbUser) {
        //保存用户
        save(tbUser);
        List<TbInterface> tbInterfaceList = tbUser.getTbInterfaceList();
        if (tbInterfaceList == null || tbInterfaceList.isEmpty()) {
            return 1;
        }
        //保存用户接口关系
        List<TbUserInterface> params = new ArrayList<>();
        for (TbInterface tbInterface : tbInterfaceList) {
            TbUserInterface tbUserInterface = new TbUserInterface();
            tbUserInterface.setUserId(tbUser.getId());
            tbUserInterface.setInterfaceId(tbInterface.getId());
            params.add(tbUserInterface);
        }
        tbUserInterfaceService.saveBatch(params);
        return tbInterfaceList.size() + 1;
    }

}
